//阿里云oss方法
const ali=require('../util/aliOSS_utils')
//token登录凭证
const jwt=require('jsonwebtoken')
//错误处理
const ApiErrorNames=require('../error/ApiErrorNames')
//数据库默认配置
const {config}=require('../config/default')
const { dataURLToFile, getByJsonp, httpRequest } = require('../util')
const mysqlModel = require('../lib/allowance')
const moment = require('moment')


/*
获取文件列表
 */
let getFileList= async (ctx,next)=>{
  const { body } = ctx.request
  const {tag,group} = body
  try{
    const token=ctx.headers.authorization
    let payload
    if (token){
      payload=await jwt.verify(token.split(' ')[1],config.secret)
      let folderName
      if(tag){
        folderName = `${payload.user_name}-${payload.user}/${tag}/`
      }
      else if(group){
        folderName = `g-${group}/`
      }
      else{
        folderName = `${payload.user_name}-${payload.user}/`
      }
      let client=ali.getClient()
      let result = await ali.getFileList(client,folderName)
      ctx.body=ApiErrorNames.getSuccessInfo(result)
    }
  }catch (e){
    ctx.body=ApiErrorNames.getErrorInfo(ApiErrorNames.INVALID_TOKEN)
  }
}

/*
上传文件
 */
let uploadImage= async (ctx,next)=>{
  const { body } = ctx.request
  const {name,path,groupName}=body
  try{
    const token=ctx.headers.authorization
    let payload
    if (token){
      payload=await jwt.verify(token.split(' ')[1],config.secret)
      let folderName
      if(!groupName){
        folderName= `${payload.user_name}-${payload.user}/`
      }
      else{
        folderName= `g-${groupName}/`
      }
      //若有传名字,则文件名为name;若没传名字,就取本地图片地址/后的后缀名
      let fName=name?`${name}.jpg`:path.split('/').pop()
      let client=ali.getClient()
      let result=await ali.upLoadFile(client,`${folderName}${fName}`,Buffer.from(path,'base64'))
      ctx.body=ApiErrorNames.getSuccessInfo(`${result.url}-上传成功`)
    }
  }catch (e){
    ctx.body=ApiErrorNames.getErrorInfo(e, ctx)
  }
}
/*
删除指定文件
 */
let deleteImage= async (ctx)=>{
  const { body } = ctx.request
  const {name}=body
  try{
    const token=ctx.headers.authorization
    let payload
    if (token){
      payload=await jwt.verify(token.split(' ')[1],config.secret)
      let folderName= `${payload.user_name}-${payload.user}/`
      //若有传名字,则文件名为name;若没传名字,就取本地图片地址/后的后缀名
      let client=ali.getClient()
      let result=await ali.deleteFile(client,`${folderName}${name}`)
      ctx.body=ApiErrorNames.getSuccessInfo(`${result}-删除成功`)
    }
  }catch (e){
    ctx.body=ApiErrorNames.getErrorInfo(e, ctx)
  }
}
/*
获取图片详细信息
 */
let getImageDetail=async (ctx)=>{
  const { body } = ctx.request
  const {url}=body
  try{
    const token=ctx.headers.authorization
    if (token){
      let result=await httpRequest(url)
      ctx.body=ApiErrorNames.getSuccessInfo(result)
    }
  }catch (e){
    ctx.body=ApiErrorNames.getErrorInfo(e, ctx)
  }
}
/*
获取版本
 */
let getFolderVer= async (ctx,next)=>{
  try{
    const token=ctx.headers.authorization
    let payload
    if (token){
      payload=await jwt.verify(token.split(' ')[1],config.secret)
      let folderName= `${payload.user_name}-${payload.user}/`
      let client=ali.getClient()
      let result = await ali.getFolderVer(client,folderName)
      ctx.body=ApiErrorNames.getSuccessInfo(result)
    }
  }catch (e){
    ctx.body=ApiErrorNames.getErrorInfo(ApiErrorNames.DATA_IS_WRONG)
  }
}
/*
给文件设置标签
 */
let setTag= async (ctx,next)=>{
  const { body } = ctx.request
  const {fileName,tagName}=body
  try{
    const token=ctx.headers.authorization
    let payload
    if (token){
      payload=await jwt.verify(token.split(' ')[1],config.secret)
      let folderName= `${payload.user_name}-${payload.user}/`
      let client=ali.getClient()
      let tagInfo= {
        USER_ID: payload.user,
        IMG_NAME: fileName,
        TAG: tagName,
        CREATED_BY: payload.user_name,
        CREATED_TIME: moment().format('YYYY-MM-DD HH:mm:ss'),
        UPDATED_BY: payload.user_name,
        UPDATED_TIME: moment().format('YYYY-MM-DD HH:mm:ss'),
      }
      await mysqlModel.setTag(tagInfo)
      await ali.copyFile(client,`${folderName}${tagName}/${fileName}`,`${folderName}${fileName}`)
      ctx.body=ApiErrorNames.getSuccessInfo(`设置标签 ${tagName} 成功`)
    }
  }catch (e){
    console.log(e)
    ctx.body=ApiErrorNames.getErrorInfo(ApiErrorNames.DATA_IS_WRONG)
  }
}
/*
文件移除标签
 */
let removeTag= async (ctx,next)=>{
  const { body } = ctx.request
  const {fileName,tagName}=body
  try{
    const token=ctx.headers.authorization
    let payload
    if (token){
      payload=await jwt.verify(token.split(' ')[1],config.secret)
      let folderName= `${payload.user_name}-${payload.user}/`
      let client=ali.getClient()
      await mysqlModel.removeTag(payload.user,fileName,tagName)
      await ali.deleteFile(client,`${folderName}${tagName}/${fileName}`)
      ctx.body=ApiErrorNames.getSuccessInfo(`移除标签 ${tagName} 成功`)
    }
  }catch (e){
    ctx.body=ApiErrorNames.getErrorInfo(ApiErrorNames.DATA_IS_WRONG)
  }
}
/*
获取当前文件标签列表
 */
let getTagList= async (ctx,next)=>{
  try{
    const token=ctx.headers.authorization
    let payload
    let fileName
    if (token){
      payload=await jwt.verify(token.split(' ')[1],config.secret)
      let result
      if(JSON.stringify(ctx.params)!=='{}'){
        fileName=ctx.params.fileName
        result=await mysqlModel.getTagList(payload.user,fileName)
      }else{
        result=await mysqlModel.getAllTagList(payload.user)
      }
      ctx.body=ApiErrorNames.getSuccessInfo(result)
    }
  }catch (e){
    ctx.body=ApiErrorNames.getErrorInfo(ApiErrorNames.DATA_IS_WRONG)
  }
}
/*
创建图像处理副本
 */

let processImage= async (ctx,next)=>{
const { body } = ctx.request
const {fileName,newName,processStr}=body
try{
  const token=ctx.headers.authorization
  let payload
  if (token){
    payload=await jwt.verify(token.split(' ')[1],config.secret)
      let folderName= `${payload.user_name}-${payload.user}/`
      let client=ali.getClient()
      await ali.processImage(client,`${folderName}${fileName}`,`${folderName}${newName}`,processStr)
      ctx.body=ApiErrorNames.getSuccessInfo(`保存至-我的相册`)
    }
  }catch (e){
    console.log(e)
    ctx.body=ApiErrorNames.getErrorInfo(ApiErrorNames.DATA_IS_WRONG)
  }
}
module.exports = {
  getFileList,
  uploadImage,
  deleteImage,
  getImageDetail,
  getFolderVer,
  setTag,
  removeTag,
  getTagList,
  processImage
}
